package com.example.managemyself.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 应用设置管理器
 * 负责管理应用的高级设置功能
 */
public class AppSettingsManager {
    
    private static final String TAG = "AppSettingsManager";
    private static final String PREFS_NAME = "app_settings";
    
    // 数据保留设置
    private static final String KEY_DATA_RETENTION_DAYS = "data_retention_days";
    private static final String KEY_AUTO_CLEANUP_ENABLED = "auto_cleanup_enabled";
    private static final String KEY_LAST_CLEANUP_DATE = "last_cleanup_date";
    
    // API配置
    private static final String KEY_WEATHER_API_KEY = "weather_api_key";
    private static final String KEY_AI_API_KEY = "ai_api_key";
    private static final String KEY_ALMANAC_API_KEY = "almanac_api_key";
    private static final String KEY_API_TIMEOUT = "api_timeout";
    private static final String KEY_API_RETRY_COUNT = "api_retry_count";
    
    // 通知设置
    private static final String KEY_NOTIFICATIONS_ENABLED = "notifications_enabled";
    private static final String KEY_TASK_REMINDERS = "task_reminders";
    private static final String KEY_DIARY_REMINDERS = "diary_reminders";
    private static final String KEY_HEALTH_REMINDERS = "health_reminders";
    
    // 隐私设置
    private static final String KEY_DATA_ENCRYPTION = "data_encryption";
    private static final String KEY_BIOMETRIC_AUTH = "biometric_auth";
    private static final String KEY_AUTO_LOCK_TIME = "auto_lock_time";
    
    // 性能设置
    private static final String KEY_CACHE_SIZE_MB = "cache_size_mb";
    private static final String KEY_IMAGE_QUALITY = "image_quality";
    private static final String KEY_ANIMATION_ENABLED = "animation_enabled";
    
    private static AppSettingsManager instance;
    private final SharedPreferences prefs;
    private final Context context;
    
    private AppSettingsManager(Context context) {
        this.context = context.getApplicationContext();
        this.prefs = this.context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    }
    
    public static synchronized AppSettingsManager getInstance(Context context) {
        if (instance == null) {
            instance = new AppSettingsManager(context);
        }
        return instance;
    }
    
    // ==================== 数据保留设置 ====================
    
    /**
     * 设置数据保留天数
     */
    public void setDataRetentionDays(int days) {
        prefs.edit().putInt(KEY_DATA_RETENTION_DAYS, days).apply();
        Log.d(TAG, "Data retention set to " + days + " days");
    }
    
    /**
     * 获取数据保留天数
     */
    public int getDataRetentionDays() {
        return prefs.getInt(KEY_DATA_RETENTION_DAYS, 365); // 默认1年
    }
    
    /**
     * 设置自动清理开关
     */
    public void setAutoCleanupEnabled(boolean enabled) {
        prefs.edit().putBoolean(KEY_AUTO_CLEANUP_ENABLED, enabled).apply();
    }
    
    /**
     * 获取自动清理开关状态
     */
    public boolean isAutoCleanupEnabled() {
        return prefs.getBoolean(KEY_AUTO_CLEANUP_ENABLED, true);
    }
    
    /**
     * 更新最后清理日期
     */
    public void updateLastCleanupDate() {
        String currentDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
        prefs.edit().putString(KEY_LAST_CLEANUP_DATE, currentDate).apply();
    }
    
    /**
     * 获取最后清理日期
     */
    public String getLastCleanupDate() {
        return prefs.getString(KEY_LAST_CLEANUP_DATE, "从未清理");
    }
    
    // ==================== API配置 ====================
    
    /**
     * 设置天气API密钥
     */
    public void setWeatherApiKey(String apiKey) {
        prefs.edit().putString(KEY_WEATHER_API_KEY, apiKey).apply();
    }
    
    /**
     * 获取天气API密钥
     */
    public String getWeatherApiKey() {
        return prefs.getString(KEY_WEATHER_API_KEY, "");
    }
    
    /**
     * 设置AI API密钥
     */
    public void setAiApiKey(String apiKey) {
        prefs.edit().putString(KEY_AI_API_KEY, apiKey).apply();
    }
    
    /**
     * 获取AI API密钥
     */
    public String getAiApiKey() {
        return prefs.getString(KEY_AI_API_KEY, "");
    }
    
    /**
     * 设置黄历API密钥
     */
    public void setAlmanacApiKey(String apiKey) {
        prefs.edit().putString(KEY_ALMANAC_API_KEY, apiKey).apply();
    }
    
    /**
     * 获取黄历API密钥
     */
    public String getAlmanacApiKey() {
        return prefs.getString(KEY_ALMANAC_API_KEY, "");
    }
    
    /**
     * 设置API超时时间（秒）
     */
    public void setApiTimeout(int timeoutSeconds) {
        prefs.edit().putInt(KEY_API_TIMEOUT, timeoutSeconds).apply();
    }
    
    /**
     * 获取API超时时间（秒）
     */
    public int getApiTimeout() {
        return prefs.getInt(KEY_API_TIMEOUT, 30); // 默认30秒
    }
    
    /**
     * 设置API重试次数
     */
    public void setApiRetryCount(int retryCount) {
        prefs.edit().putInt(KEY_API_RETRY_COUNT, retryCount).apply();
    }
    
    /**
     * 获取API重试次数
     */
    public int getApiRetryCount() {
        return prefs.getInt(KEY_API_RETRY_COUNT, 3); // 默认3次
    }
    
    // ==================== 通知设置 ====================
    
    /**
     * 设置通知总开关
     */
    public void setNotificationsEnabled(boolean enabled) {
        prefs.edit().putBoolean(KEY_NOTIFICATIONS_ENABLED, enabled).apply();
    }
    
    /**
     * 获取通知总开关状态
     */
    public boolean isNotificationsEnabled() {
        return prefs.getBoolean(KEY_NOTIFICATIONS_ENABLED, true);
    }
    
    /**
     * 设置任务提醒
     */
    public void setTaskRemindersEnabled(boolean enabled) {
        prefs.edit().putBoolean(KEY_TASK_REMINDERS, enabled).apply();
    }
    
    /**
     * 获取任务提醒状态
     */
    public boolean isTaskRemindersEnabled() {
        return prefs.getBoolean(KEY_TASK_REMINDERS, true);
    }
    
    /**
     * 设置日记提醒
     */
    public void setDiaryRemindersEnabled(boolean enabled) {
        prefs.edit().putBoolean(KEY_DIARY_REMINDERS, enabled).apply();
    }
    
    /**
     * 获取日记提醒状态
     */
    public boolean isDiaryRemindersEnabled() {
        return prefs.getBoolean(KEY_DIARY_REMINDERS, true);
    }
    
    /**
     * 设置健康提醒
     */
    public void setHealthRemindersEnabled(boolean enabled) {
        prefs.edit().putBoolean(KEY_HEALTH_REMINDERS, enabled).apply();
    }
    
    /**
     * 获取健康提醒状态
     */
    public boolean isHealthRemindersEnabled() {
        return prefs.getBoolean(KEY_HEALTH_REMINDERS, true);
    }
    
    // ==================== 隐私设置 ====================
    
    /**
     * 设置数据加密
     */
    public void setDataEncryptionEnabled(boolean enabled) {
        prefs.edit().putBoolean(KEY_DATA_ENCRYPTION, enabled).apply();
    }
    
    /**
     * 获取数据加密状态
     */
    public boolean isDataEncryptionEnabled() {
        return prefs.getBoolean(KEY_DATA_ENCRYPTION, false);
    }
    
    /**
     * 设置生物识别认证
     */
    public void setBiometricAuthEnabled(boolean enabled) {
        prefs.edit().putBoolean(KEY_BIOMETRIC_AUTH, enabled).apply();
    }
    
    /**
     * 获取生物识别认证状态
     */
    public boolean isBiometricAuthEnabled() {
        return prefs.getBoolean(KEY_BIOMETRIC_AUTH, false);
    }
    
    /**
     * 设置自动锁定时间（分钟）
     */
    public void setAutoLockTime(int minutes) {
        prefs.edit().putInt(KEY_AUTO_LOCK_TIME, minutes).apply();
    }
    
    /**
     * 获取自动锁定时间（分钟）
     */
    public int getAutoLockTime() {
        return prefs.getInt(KEY_AUTO_LOCK_TIME, 15); // 默认15分钟
    }
    
    // ==================== 性能设置 ====================
    
    /**
     * 设置缓存大小（MB）
     */
    public void setCacheSizeMB(int sizeMB) {
        prefs.edit().putInt(KEY_CACHE_SIZE_MB, sizeMB).apply();
    }
    
    /**
     * 获取缓存大小（MB）
     */
    public int getCacheSizeMB() {
        return prefs.getInt(KEY_CACHE_SIZE_MB, 100); // 默认100MB
    }
    
    /**
     * 设置图片质量（0-100）
     */
    public void setImageQuality(int quality) {
        prefs.edit().putInt(KEY_IMAGE_QUALITY, quality).apply();
    }
    
    /**
     * 获取图片质量（0-100）
     */
    public int getImageQuality() {
        return prefs.getInt(KEY_IMAGE_QUALITY, 80); // 默认80%
    }
    
    /**
     * 设置动画开关
     */
    public void setAnimationEnabled(boolean enabled) {
        prefs.edit().putBoolean(KEY_ANIMATION_ENABLED, enabled).apply();
    }
    
    /**
     * 获取动画开关状态
     */
    public boolean isAnimationEnabled() {
        return prefs.getBoolean(KEY_ANIMATION_ENABLED, true);
    }
    
    // ==================== 工具方法 ====================
    
    /**
     * 重置所有设置为默认值
     */
    public void resetAllSettings() {
        prefs.edit().clear().apply();
        Log.d(TAG, "All settings reset to default");
    }
    
    /**
     * 导出设置为JSON字符串
     */
    public String exportSettings() {
        // 这里可以实现设置的导出功能
        return "设置导出功能开发中...";
    }
    
    /**
     * 从JSON字符串导入设置
     */
    public boolean importSettings(String settingsJson) {
        // 这里可以实现设置的导入功能
        Log.d(TAG, "Settings import feature in development");
        return false;
    }
    
    /**
     * 获取设置统计信息
     */
    public SettingsStatistics getSettingsStatistics() {
        return new SettingsStatistics(
                getDataRetentionDays(),
                isAutoCleanupEnabled(),
                isNotificationsEnabled(),
                isDataEncryptionEnabled(),
                getCacheSizeMB()
        );
    }
    
    /**
     * 设置统计信息类
     */
    public static class SettingsStatistics {
        private final int dataRetentionDays;
        private final boolean autoCleanupEnabled;
        private final boolean notificationsEnabled;
        private final boolean dataEncryptionEnabled;
        private final int cacheSizeMB;
        
        public SettingsStatistics(int dataRetentionDays, boolean autoCleanupEnabled,
                                boolean notificationsEnabled, boolean dataEncryptionEnabled,
                                int cacheSizeMB) {
            this.dataRetentionDays = dataRetentionDays;
            this.autoCleanupEnabled = autoCleanupEnabled;
            this.notificationsEnabled = notificationsEnabled;
            this.dataEncryptionEnabled = dataEncryptionEnabled;
            this.cacheSizeMB = cacheSizeMB;
        }
        
        // Getters
        public int getDataRetentionDays() { return dataRetentionDays; }
        public boolean isAutoCleanupEnabled() { return autoCleanupEnabled; }
        public boolean isNotificationsEnabled() { return notificationsEnabled; }
        public boolean isDataEncryptionEnabled() { return dataEncryptionEnabled; }
        public int getCacheSizeMB() { return cacheSizeMB; }
    }
} 